package com.soa.demo.util;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.zip.GZIPInputStream;

public class GetWeather {
    public static final String key = "6cbc4992b45e4fb7b6dcd6387ece35c0";
    public static Map<String,String> getWeather(String city){
        ArrayList<String> cityLocation = getLocation(city);
        if (!cityLocation.get(0).equals("200")){
            return null;
        }
        Map<String,String> map = getWeatherByHFTQ(cityLocation.get(1));
        map.put("adm1", cityLocation.get(2));
        map.put("citycode", cityLocation.get(1));
        return map;
    }


    /**
     * 从和风天气获取天气信息
     *
     * @param location 城市编码
     * @return
     */
    public static Map<String,String> getWeatherByHFTQ(String location) {
        Map<String,String> map = new HashMap<String,String>();

        StringBuffer sb = new StringBuffer();
        try {
            String weather_url =
                    "https://devapi.qweather.com/v7/weather/3d?location=" + location + "&key=" + key;
            URL url = new URL(weather_url);
            URLConnection conn = url.openConnection();
            InputStream is = conn.getInputStream();
            GZIPInputStream gzin = new GZIPInputStream(is);
            InputStreamReader isr = new InputStreamReader(gzin, StandardCharsets.UTF_8); // 设置读取流的编码格式，自定义编码
            BufferedReader reader = new BufferedReader(isr);
            String line = null;
            while ((line = reader.readLine()) != null) {
                sb.append(line + " ");
            }
            reader.close();

            // 解析JSON格式的天气信息数据
            JSONObject json = JSONObject.parseObject(sb.toString());
            String code = json.getString("code");
            map.put("code", code);
            JSONObject firstDayWeather = json.getJSONArray("daily").getJSONObject(0);
            String obsTime = firstDayWeather.getString("fxDate");//数据观测时间
            map.put("obsTime",obsTime);
            String tempMax = firstDayWeather.getString("tempMax"); // 获取最高温度
            map.put("tempMax",tempMax);
            String tempMin = firstDayWeather.getString("tempMin"); // 获取最低温度
            map.put("tempMin",tempMin);
            String textDay = firstDayWeather.getString("textDay"); //天气状况的文字描述，包括阴晴雨雪等天气状态的描述
            map.put("textDay",textDay);

        } catch (Exception e) {
            System.out.println("获取天气信息失败：" + e);
        }

        return map;
    }


    public static ArrayList<String> getLocation(String city){
        String id = "";
        String adm1 = "";
        ArrayList<String> list = new ArrayList<String>();
        list.add("999");
        StringBuffer sb = new StringBuffer();
        try {
            String weather_url =
                    "https://geoapi.qweather.com/v2/city/lookup?location=" + URLEncoder.encode(city, StandardCharsets.UTF_8) + "&key=" + key;
            URL url = new URL(weather_url);
            URLConnection conn = url.openConnection();
            InputStream is = conn.getInputStream();
            GZIPInputStream gzin = new GZIPInputStream(is);
            InputStreamReader isr = new InputStreamReader(gzin, StandardCharsets.UTF_8); // 设置读取流的编码格式，自定义编码
            BufferedReader reader = new BufferedReader(isr);
            String line = null;
            while ((line = reader.readLine()) != null) {
                sb.append(line + " ");
            }
            reader.close();

            // 解析JSON格式的天气信息数据
            JSONObject json = JSONObject.parseObject(sb.toString());
            String code = json.getString("code");
            JSONArray location = json.getJSONArray("location");
            JSONObject Fir = location.getJSONObject(0);
            id = Fir.getString("id"); //获取城市id
            adm1 = Fir.getString("adm1"); //获取城市所属一级行政区域
            list.set(0,code);
            list.add(id);
            list.add(adm1);
            // 输出获取到的天气信息
            System.out.println("code："+code);
            System.out.println("城市id："+id);
            System.out.println("城市所属一级行政区域："+adm1);

        } catch (Exception e) {
            System.out.println("获取天气信息失败：" + e);
            return list;
        }

        return list;
    }

//    public static void main(String[] args) {
//        String city = "北京";
//        Map<String,String> map = getWeather(city);
//        for (String key : map.keySet()) {
//            System.out.println(key+":" + map.get(key));
//        }
//    }
}